package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.investment.domain.Dividend;
import com.lysj.bhp.investment.dto.DividendDto;
import com.lysj.bhp.investment.vo.DividendVo;
import com.lysj.bhp.user.domain.WalletEditLog;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiDividedRecordController", tags = "分红收益模块接口")
public class ApiDividedRecordController extends ApiContent {

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }


    /**
     * @author drj
     * @date 2018/10/11 14:22
     * @Description:分红记录
     */
    @ApiOperation(value = "分红利息记录")
    @GetMapping("/show_divided_record")
    public Resp showDividedRecord(DividendDto model) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(5);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (model.getBegin_createTime() == null) {
            model.setBegin_createTime(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_createTime(FormatUtil.getDayStartDay(model.getBegin_createTime()));
        }
        if (model.getEnd_createTime() == null) {
            model.setEnd_createTime(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_createTime(FormatUtil.getDayEndDay(model.getEnd_createTime()));
        }
        //获取根据时间以及币种查询出的充值记录
        Pageable pageable = new PageRequest(model.getPage(), model.getLimit());
        model.setUserId(currentUser().getUserId());// 当前登录用户的充值记录
        Page<DividendVo> dividendVoPage = investmentContent.dividendRepository.findUserDividedRecord(pageable, model.getBegin_createTime(), model.getEnd_createTime(), model.getUserId());
        for (DividendVo dividendVo : dividendVoPage.getContent()) {
            if (1 == model.getLanguageType()) {
                dividendVo.setDividendName("利息");
            } else {
                dividendVo.setDividendName("Dividends History");
            }
            dividendVo.setWalletType(20);
            dividendVo.setAmount(dividendVo.getAmount().setScale(6, BigDecimal.ROUND_DOWN));
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", dividendVoPage.getTotalPages());
        respMap.put("rows", dividendVoPage.getContent());
        return new Resp(respMap);
    }


    /**
     * @author drj
     * @date 2018/10/11 14:22
     * @Description：打币记录
     */
    @ApiOperation(value = "打币记录", notes = "钱包类型：Integer walletType 10:btc,110:bhpc_bouns")
    @GetMapping("/show_wallet_edit_log_record")
    public Resp showWalletEditLogRecord(DividendDto model) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(5);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (model.getBegin_createTime() == null) {
            model.setBegin_createTime(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_createTime(FormatUtil.getDayStartDay(model.getBegin_createTime()));
        }
        if (model.getEnd_createTime() == null) {
            model.setEnd_createTime(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_createTime(FormatUtil.getDayEndDay(model.getEnd_createTime()));
        }
        //获取根据时间以及币种查询出的充值记录
        Pageable pageable = new PageRequest(model.getPage(), model.getLimit());
        model.setUserId(currentUser().getUserId());// 当前登录用户的充值记录
        Page<DividendVo> dividendVoPage = userContent.walletEditLogRepository.findUserWalletEditRecord(pageable, model.getBegin_createTime(), model.getEnd_createTime(), model.getUserId(), model.getWalletType());
        for (DividendVo dividendVo : dividendVoPage.getContent()) {
            if (10 == model.getWalletType()) {
                if (1 == model.getLanguageType()) {
                    dividendVo.setDividendName("节点分红");
                } else {
                    dividendVo.setDividendName("Supernode Dividends");
                }
            }
            if (110 == model.getWalletType()) {
                if (1 == model.getLanguageType()) {
                    dividendVo.setDividendName("奖励");
                } else {
                    dividendVo.setDividendName("Reward Dividends");
                }
            }
            //若选择打币方式为减币,则数量为负数
            if (2 == dividendVo.getOperation()) {
                dividendVo.setAmount(dividendVo.getAmount().multiply(new BigDecimal("-1")));
            }
            dividendVo.setAmount(dividendVo.getAmount().setScale(6, BigDecimal.ROUND_DOWN));
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", dividendVoPage.getTotalPages());
        respMap.put("rows", dividendVoPage.getContent());
        return new Resp(respMap);
    }

    @ApiOperation(value = "全部记录")
    @GetMapping("/show_all_dividend_record")
    public Resp showAllDividendRecord(DividendDto model) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(5);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (model.getBegin_createTime() == null) {
            model.setBegin_createTime(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_createTime(FormatUtil.getDayStartDay(model.getBegin_createTime()));
        }
        if (model.getEnd_createTime() == null) {
            model.setEnd_createTime(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_createTime(FormatUtil.getDayEndDay(model.getEnd_createTime()));
        }
        List<DividendVo> dividendVos = new LinkedList<>();
        //获取所有的分红记录
        List<Dividend> dividendList = investmentContent.dividendRepository.findByUserIdOrderByCreateTimeDesc(currentUser().getUserId());
        for (Dividend dividend : dividendList) {
            DividendVo dividendVo = new DividendVo();
            if (1 == model.getLanguageType()) {
                dividendVo.setDividendName("利息");
            } else {
                dividendVo.setDividendName("Dividends History");
            }
            dividendVo.setWalletType(20);
            dividendVo.setAmount(dividend.getDividend().setScale(6, BigDecimal.ROUND_DOWN));
            dividendVo.setCreateTime(dividend.getCreateTime());
            dividendVos.add(dividendVo);
        }
        //获取BTC以及奖励金打币记录
        Integer[] typeIds = new Integer[2];
        typeIds[0] = 10;
        typeIds[1] = 110;
        List<WalletEditLog> walletEditLogList = userContent.walletEditLogRepository.findByUserIdAndWalletTypeIn(currentUser().getUserId(), typeIds);
        for (WalletEditLog walletEditLog : walletEditLogList) {
            DividendVo dividendVo = new DividendVo();
            if (10 == walletEditLog.getWalletType()) {
                if (1 == model.getLanguageType()) {
                    dividendVo.setDividendName("节点分红");
                } else {
                    dividendVo.setDividendName("Supernode Dividends");
                }
            }
            if (110 == walletEditLog.getWalletType()) {
                if (1 == model.getLanguageType()) {
                    dividendVo.setDividendName("奖励");
                } else {
                    dividendVo.setDividendName("Reward Dividends");
                }
            }
            dividendVo.setWalletType(walletEditLog.getWalletType());
            //若选择打币方式为减币,则数量为负数
            if (2 == walletEditLog.getOperation()) {
                walletEditLog.setAmount(walletEditLog.getAmount().multiply(new BigDecimal("-1")));
            }
            dividendVo.setAmount(walletEditLog.getAmount().setScale(6, BigDecimal.ROUND_DOWN));
            dividendVo.setCreateTime(walletEditLog.getEditDate());
            dividendVos.add(dividendVo);
        }
        //筛选出符合条件的记录
        dividendVos = dividendVos.stream().filter(item -> item.getCreateTime().getTime() >= model.getBegin_createTime().getTime()
                && item.getCreateTime().getTime() <= model.getEnd_createTime().getTime()).collect(Collectors.toList());
        //按照时间倒叙排列
        Collections.sort(dividendVos, (o1, o2) -> (o2.getCreateTime().compareTo(o1.getCreateTime()))
        );
        Map<String, Object> respMap = new HashMap();
        int count = dividendVos.size();
        respMap.put("totalpage", count % model.getLimit() == 0 ? count / model.getLimit() : count / model.getLimit() + 1);
        //数据总数小于每页显示的数据条数
        if (model.getPage() == 0) {
            if (count <= model.getLimit())  //数据总数小于每页显示的数据条数
            {
                //截止到总的数据条数(当前数据不足一页，按一页显示)，这样才不会出现数组越界异常
                respMap.put("rows", dividendVos.subList(0, count));
            } else {
                respMap.put("rows", dividendVos.subList(0, model.getLimit()));
            }

        }
        //截取起始下标
        int fromIndex = model.getPage() * model.getLimit();
        //截取截止下标
        int toIndex = model.getPage() * model.getLimit() + model.getLimit();
        //若当前请求条数小于等于总条数
        if (fromIndex <= count) {
            if (count < toIndex) {
                respMap.put("rows", dividendVos.subList(fromIndex, count));
            } else {
                respMap.put("rows", dividendVos.subList(model.getPage() * model.getLimit(), model.getPage() * model.getLimit() + model.getLimit()));
            }
        } else {
            respMap.put("rows", "");
        }
        return new Resp(respMap);
    }
}
